package com.javaweb.common.utils;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 请求开放平台套件授权相关接口的加签类
 */
public class SignHelper {

    /**
     * 按参数名排序后依次拼接参数名称与数值，之后对该字符串使用 HmacSHA256 加签，加签结果进行 base 64 返回
     *
     * @param params      请求参数 map
     * @param suiteSecret 套件密钥，用作 mac key
     * @return 签名
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     */
    public static String sign(Map<String, String> params, String suiteSecret) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        // use tree map to sort params by name
        Map<String, String> treeMap;
        if (params instanceof TreeMap) {
            treeMap = params;
        } else {
            treeMap = new TreeMap<>(params);
        }

        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, String> entry : treeMap.entrySet()) {
            stringBuilder.append(entry.getKey()).append(entry.getValue());
        }

        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(suiteSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        System.out.println("stringBuilder.toString() = " + stringBuilder.toString());
        byte[] signData = mac.doFinal(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
        String base64String = Base64.getEncoder().encodeToString(signData);
        return URLEncoder.encode(base64String, "UTF-8");
    }

    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        StringBuffer url = new StringBuffer("https://dbox.diwork.com/iuap-api-auth/open-auth/selfAppAuth/getAccessToken?a=1");
        String appSecret = "a459df9c3648449da0e54ae85eac7c32";
        Map<String, String> params = new HashMap<>();
        String timeMillis = String.valueOf(System.currentTimeMillis());
        System.out.println("timeMillis = " + timeMillis);

        // 除签名外的其他参数
        params.put("appKey", "b7a1c3a02a744998b0465fa7f2c3bdf8");
        params.put("timestamp", timeMillis);
        // 计算签名
        String signature = SignHelper.sign(params, appSecret);
        params.put("signature", signature);
        params.forEach((key, value) -> {
            url.append("&");
            url.append(key);
            url.append("=");
            url.append(value);
        });
        System.out.println(url.toString());
        String body = HttpUtil.createGet(url.toString()).execute().body();

        System.out.println(url);
        System.out.println(timeMillis);
        System.out.println("signature = " + signature);
        System.out.println(body);
    }

}
